package com.mediacloud.app.newsmodule.fragment.baoliao.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.Html
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.location.BDLocation
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.PoiInfo
import com.baidu.mapapi.search.poi.*
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener
import com.baidu.mapapi.search.sug.SuggestionSearch
import com.baidu.mapapi.search.sug.SuggestionSearchOption
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.views.EditTextWithDel
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.interfaces.ILocation
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.utils.DefaultBgUtil
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.view.XSmartRefreshLayout
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList
import kotlin.collections.set


const val REQUEST_CODE = 12358
const val LOCATION_REQUEST_CODE = 12359
/**
 * 开启定位服务
 * */
const val LOCATION_SERVER_REQUEST_CODE = 12360
const val REQUEST_KEY = "location"

class BaoLiaoLocationActivity : BaseBackActivity() {
    private lateinit var recyclerView: androidx.recyclerview.widget.RecyclerView
    private lateinit var searchRecyclerView: androidx.recyclerview.widget.RecyclerView
    private var checkPosition = 0

    //创建poi检索实例
    private var poiSearch = PoiSearch.newInstance()
    //创建poi监听者
    private var poiListener = object:OnGetPoiSearchResultListener {


        override fun onGetPoiIndoorResult(p0: PoiIndoorResult?) {
        }

        override fun onGetPoiDetailResult(p0: PoiDetailResult) {
        }

        override fun onGetPoiDetailResult(p0: PoiDetailSearchResult?) {

        }

        @Override
        override fun onGetPoiResult(result: PoiResult) {
            closeStateView()
            //获取POI检索结果
            if(loadIndex == 0){
                xSmartRefreshLayout?.finishRefresh()
                val list =  ArrayList<PoiInfo>()
                if(!isSearch){

                    //第一条为不显示位置
                    val nonePoi = PoiInfo()
                    nonePoi.name = getString(R.string.none_loaction)
                    nonePoi.address = ""
                    list.add(nonePoi)
                    checkPosition=1//检索到了的话默认显示我的地址
                    val poi = PoiInfo()
                    poi.name = getString(R.string.my_location)
                    poi.address = AppFactoryGlobalConfig.getAddressStr()
                    poi.location = LatLng(AppFactoryGlobalConfig.getLatitude().toDouble(),AppFactoryGlobalConfig.getLongitude().toDouble())
                    list.add(poi)
                }
                if(result.allPoi !=null){
                    list.addAll(result.allPoi)
                }
                recyclerAdapter?.data?.clear()
                recyclerAdapter?.data?.addAll(list)
                recyclerAdapter?.notifyDataSetChanged()
            }else{
                xSmartRefreshLayout?.finishLoadMore()
                if(result.allPoi !=null){
                    recyclerAdapter?.data?.addAll(result.allPoi)
                }
                recyclerAdapter?.notifyDataSetChanged()
            }

        }

    }
    private var onGetSuggestionResultListener :OnGetSuggestionResultListener?=null
    private var mSuggestionSearch:SuggestionSearch? = SuggestionSearch.newInstance()
    private var loadIndex = 0
    private var recyclerAdapter:RecyclerAdapter? = null
    private var searchRecyclerAdapter:MySearchRecyclerAdapter? = null
    private var xSmartRefreshLayout:XSmartRefreshLayout? = null
    private var searchXSmartRefreshLayout:XSmartRefreshLayout? = null
    private var keyWord :String?= ""
    private var searchEdit: EditTextWithDel? = null
    private var isSearch = false
    /**
     * true  :文字搜索结果
     * false :文字搜索结果再次搜索
     * */
    var searchType = true
    /**
     * 搜索内容
     * */
    private var searchContent:View? = null

    /**
     * 假的搜索View
     * */
    private var showSearchView:View? = null

    private var viewCancel:TextView? = null



    override fun getLayoutResID(): Int {
        return R.layout.activity_bao_liao_location
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
    }



    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    fun isLocationEnabled():Boolean{
        return  Utility.isOPenGPS(this)
//        val locationManager:LocationManager = getSystemService(LOCATION_SERVICE) as LocationManager
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ){
//            return locationManager.isLocationEnabled
//        }else{
//
//        }
//
//        var locationMode = 0
//        var locationProviders:String = ""
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            try {
//                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE)
//            } catch (e:Settings.SettingNotFoundException ) {
//                e.printStackTrace()
//                return false
//            }
//            return locationMode != Settings.Secure.LOCATION_MODE_OFF
//        } else {
//            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
//            return !TextUtils.isEmpty(locationProviders)
//        }
    }





    fun initView(){
        setTitle(getString(R.string.loaction))
        loadingView = Utility.findViewById(mRootView, R.id.mLoadingView)
        initStateView()
        loadingView.setOnClickListener {
            if (TYPE_LOADING != currentState) {
                showStateView(TYPE_LOADING, false)
                initDefaultList()
            }
        }
        xSmartRefreshLayout = findViewById(R.id.x_smart_refresh_layout)
        xSmartRefreshLayout?.setEnableRefresh(true)
        xSmartRefreshLayout?.setEnableLoadMore(true)
        xSmartRefreshLayout?.setOnRefreshListener {
            loadIndex = 0
            nearbyPoiSearch(keyWord)
        }
        xSmartRefreshLayout?.setOnLoadMoreListener {
            loadIndex ++
            nearbyPoiSearch(keyWord)
        }
        recyclerView = findViewById(R.id.location_recycler_view)
        recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, false)
        initDefaultList()
        viewCancel = findViewById(R.id.cancel)
        viewCancel?.setTextColor(DefaultBgUtil.getTintColor(this))
        viewCancel?.setOnClickListener {
            closeSearch()
        }
        mMoreText.visibility = View.VISIBLE
        setMoreText("确认")
        initSearchView()
    }


    fun initDefaultList()
    {
        if(AppFactoryGlobalConfig.location != null &&AppFactoryGlobalConfig.location.address!=null &&AppFactoryGlobalConfig.location.address.address!=null){

            val list =  ArrayList<PoiInfo>()
            //第一条为不显示位置
            val nonePoi = PoiInfo()
            nonePoi.name = getString(R.string.none_loaction)
            nonePoi.address = ""
            list.add(nonePoi)
            checkPosition=1//检索到了的话默认显示我的地址

            val poi = PoiInfo()
            poi.name = getString(R.string.my_location)
            poi.address = AppFactoryGlobalConfig.getAddressStr()
            list.add(poi)
            recyclerAdapter = RecyclerAdapter(list,this@BaoLiaoLocationActivity)
            recyclerView.adapter = recyclerAdapter
            keyWord =AppFactoryGlobalConfig.getAddressStr()
            nearbyPoiSearch(keyWord)
        }else{

            PermissionUtil.getLocation(this,object:ILocation{
                override fun onLocation(location: BDLocation) {
                    val poi = PoiInfo()
                    poi.name = getString(R.string.my_location)
                    poi.address = location.addrStr
                    val list =  ArrayList<PoiInfo>()
                    //第一条为不显示位置
                    val nonePoi = PoiInfo()
                    nonePoi.name = getString(R.string.none_loaction)
                    nonePoi.address = ""
                    list.add(nonePoi)
                    checkPosition=1//检索到了的话默认显示我的地址

                    list.add(poi)
                    recyclerAdapter = RecyclerAdapter(list,this@BaoLiaoLocationActivity)
                    recyclerView.adapter = recyclerAdapter
                    keyWord = AppFactoryGlobalConfig.getAddressStr()
                    nearbyPoiSearch(keyWord)
                }

                override fun onFail() {
                    showStateView(TYPE_NO_CONTENT,false)
                }
            })

        }
    }




    override fun moreClicked() {
        val intent = Intent()
        try {
            intent.putExtra(REQUEST_KEY,recyclerAdapter?.data?.get(checkPosition))
            setResult(REQUEST_CODE,intent)
        }catch (e:Exception){

        }
        finish()
    }

    private fun initSearchView() {
        searchXSmartRefreshLayout = findViewById(R.id.search_x_smart_refresh_layout)
        searchXSmartRefreshLayout?.setEnableRefresh(true)
        searchXSmartRefreshLayout?.setEnableLoadMore(true)
        searchXSmartRefreshLayout?.setOnRefreshListener {

        }
        searchXSmartRefreshLayout?.setOnLoadMoreListener {

        }
        searchRecyclerView = findViewById(R.id.search_location_recycler_view)
        searchRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, false)
        searchRecyclerAdapter = MySearchRecyclerAdapter(ArrayList(),this)
        searchRecyclerView.adapter = searchRecyclerAdapter
        searchEdit = findViewById(R.id.searchText)
        searchEdit?.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(searchEdit?.text.toString())) {
//                    if(AppFactoryGlobalConfig.location != null){
//                        sugSearch(searchEdit?.text.toString())
//                    }
                   // sugSearch(searchEdit?.text.toString())
                }else{
//                    searchRecyclerAdapter?.data?.clear()
//                    searchRecyclerAdapter?.notifyDataSetChanged()
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                Log.w(TAG, "beforeTextChanged")
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Log.w(TAG, "onTextChanged")
            }
        })
        searchEdit?.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            val b =
                actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER
            if (b && !TextUtils.isEmpty(searchEdit?.text)) {
                sugSearch(searchEdit?.text.toString())
                return@OnEditorActionListener true
            }else{
                searchRecyclerAdapter?.data?.clear()
                searchRecyclerAdapter?.notifyDataSetChanged()
            }
            false
        })
        showSearchView = findViewById(R.id.linear_search_box)
        /*findViewById<View>(R.id.top_search_container).setBackgroundColor(AppFactoryGlobalConfig.getAppServerConfigInfo(this).mainColor)
        val customDetailNavigateBgColor = AppFactoryGlobalConfig.getAppServerConfigInfo(this).customDetailNavigateBgColor
        if (needSetTopBgColor() && !TextUtils.isEmpty(customDetailNavigateBgColor) && customDetailNavigateBgColor.startsWith("#")) {
            findViewById<View>(R.id.top_search_container).setBackgroundColor(Color.parseColor(customDetailNavigateBgColor))
        }*/
        searchContent = findViewById(R.id.search_mask_view)
        showSearchView?.setOnClickListener {
            showSearch()
        }
    }

    private fun showSearch(){
        searchContent?.visibility = View.VISIBLE
        showSearchView?.visibility = View.INVISIBLE
        searchEdit?.requestFocus()
        showKeyBoard()
    }

    private fun hintKeyBoard() {
        //拿到InputMethodManager
        val imm:InputMethodManager= getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //如果window上view获取焦点 && view不为空
        if(imm.isActive && currentFocus !=null){
            //拿到view的token 不为空
            if (currentFocus!!.windowToken !=null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
            }
         }
    }

    private fun showKeyBoard() {
        //拿到InputMethodManager
        val imm:InputMethodManager= getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //如果window上view获取焦点 && view不为空
        if(imm.isActive && currentFocus !=null){
            if (currentFocus!!.windowToken !=null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.showSoftInput(searchEdit,InputMethodManager.SHOW_FORCED)
            }
        }
    }

    fun closeSearch(){
        searchContent?.visibility = View.GONE
        showSearchView?.visibility = View.VISIBLE
        searchRecyclerAdapter?.data?.clear()
        searchRecyclerAdapter?.notifyDataSetChanged()
        searchEdit?.setText("")
        hintKeyBoard()
    }

    /**
     * 关键词搜索
     * */
    fun sugSearch(keyWord: String){
        if(onGetSuggestionResultListener == null){
            onGetSuggestionResultListener = OnGetSuggestionResultListener { suggestionResult ->
                //处理sug检索结果
                if(suggestionResult.allSuggestions == null){
                    Log.w(TAG,"sugSearch onGetSuggestionResultListener onGetSuggestionResult suggestionResult.allSuggestions is null")
                    hideKeyBroad()
                    return@OnGetSuggestionResultListener
                }
                searchXSmartRefreshLayout?.setEnableLoadMore(false)
                searchXSmartRefreshLayout?.setEnableRefresh(false)
                searchXSmartRefreshLayout?.setBackgroundColor(Color.WHITE)
                searchType = true
                val list = ArrayList<PoiInfo>()
                for (suggestionInfo in suggestionResult.allSuggestions){
                    val item = PoiInfo()
                    item.name = suggestionInfo.key
                    item.city = suggestionInfo.city
                    item.location = suggestionInfo.pt
                    item.uid = suggestionInfo.uid
                    item.address = suggestionInfo.city+suggestionInfo.district
                    list.add(item)
                }
                searchRecyclerAdapter?.data?.clear()
                searchRecyclerAdapter?.data?.addAll(list)
                searchRecyclerAdapter?.notifyDataSetChanged()
            }
            mSuggestionSearch?.setOnGetSuggestionResultListener(onGetSuggestionResultListener)
        }
        if (AppFactoryGlobalConfig.location != null)
            mSuggestionSearch?.requestSuggestion(SuggestionSearchOption()
                    .city(AppFactoryGlobalConfig.location.city)
                    .keyword(keyWord))
        else{
            mSuggestionSearch?.requestSuggestion(SuggestionSearchOption()
                    .city("成都市")
                    .keyword(keyWord))
        }
    }

    /**
     * 周边poi检索示例
     */
    fun nearbyPoiSearch(keyWord: String?,location:LatLng? = null) {
            if(keyWord==null) return

        //设置poi监听者该方法要先于检索方法searchNearby(PoiNearbySearchOption)前调用，否则会在某些场景出现拿不到回调结果的情况
        poiSearch.setOnGetPoiSearchResultListener(poiListener)
        //设置请求参数
        val nearbySearchOption = PoiNearbySearchOption()
                .keyword(keyWord)//检索关键字
                .sortType(PoiSortType.distance_from_near_to_far)
                .location(location ?: LatLng(AppFactoryGlobalConfig.location.latitude, AppFactoryGlobalConfig.location.longitude))//检索位置
                .pageNum(loadIndex)//分页编号，默认是0页
                .pageCapacity(20)//设置每页容量，默认10条
                .radius(5000)//附近检索半径
        //发起请求
        poiSearch.searchNearby(nearbySearchOption)

    }

    override fun onDestroy() {
        super.onDestroy()
        //释放检索对象
        poiSearch.destroy()
        mSuggestionSearch?.destroy()
    }

    open inner class RecyclerAdapter(data: MutableList<PoiInfo>?, context: Context?) : BaseRecyclerAdapter<PoiInfo>(data, context) {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
            val view = layoutInflater?.inflate(R.layout.bao_liao_location_item,null,false)
            return MyViewHolder(view!!)
        }

        override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
            if(holder is MyViewHolder){
                holder.onBingViewHolder(position,getItem(position))
            }
        }

    }

    open inner class MyViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView){
        var tvTitle:TextView? = null
        var tvDetail:TextView? = null
        var imageChecked:ImageView? = null

        open fun onBingViewHolder(position:Int,poi:PoiInfo){
            setItemViewClickListener(position, poi)
            itemView.setBackgroundColor(Color.WHITE)
            tvTitle = itemView?.findViewById(R.id.tv_title)
            tvDetail = itemView?.findViewById(R.id.tv_detail)
            imageChecked = itemView?.findViewById(R.id.image_check)
            showCheckedPosition(position)
            tvTitle?.text = poi.name
            tvDetail?.text = poi.address
            if(TextUtils.isEmpty(poi.address))
            {
                tvDetail?.visibility=View.GONE
            }
            else
            {
                tvDetail?.visibility=View.VISIBLE
            }
        }

        open fun showCheckedPosition(position: Int) {
            if (position == checkPosition) {
                imageChecked?.visibility = View.VISIBLE
            } else {
                imageChecked?.visibility = View.GONE
            }
        }

        open fun setItemViewClickListener(position: Int, poi: PoiInfo) {
            itemView.setOnClickListener {
                checkPosition = position
                recyclerView.adapter!!.notifyDataSetChanged()
            }
        }
    }

    inner class MySearchRecyclerAdapter(data: MutableList<PoiInfo>?, context: Context?) : RecyclerAdapter(data, context) {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
            val view = layoutInflater?.inflate(R.layout.bao_liao_location_item,null,false)
            return MySearchViewHolder(view!!)
    }

        override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
            if(holder is MySearchViewHolder){
                holder.onBingViewHolder(position,getItem(position))
            }
        }
    }

    inner class MySearchViewHolder(itemView: View):MyViewHolder(itemView){
        override fun setItemViewClickListener(position: Int, poi: PoiInfo) {
            itemView.setOnClickListener {
                loadIndex = 0
                isSearch = true
                checkPosition = 0
                keyWord = poi.name
                nearbyPoiSearch(keyWord,poi.location)
                closeSearch()
            }
        }

        override fun onBingViewHolder(position: Int, poi: PoiInfo) {
            super.onBingViewHolder(position, poi)
            tvDetail?.text = poi.address
            var titleText = poi.name
            val pattern = Pattern.compile("(?i)${searchEdit?.text.toString()}")
            val matcher = pattern.matcher(titleText)
            val map = HashMap<String, String>()
            while (matcher.find()) {
                map[matcher.group()] = matcher.group()
            }
            val e = map.entries
            val iterator = e.iterator()
            while (iterator.hasNext()) {
                val replaceString = iterator.next().key
                titleText = titleText.replace(replaceString.toRegex(), replaceString(replaceString,resources.getDimension(R.dimen.sp_17).toInt()))
            }
            tvTitle?.text = Html.fromHtml(titleText)
        }

        private fun replaceString(keyString: String,fontSize:Int): String {
            return "<font color=\"" + AppFactoryGlobalConfig.getAppServerConfigInfo(this@BaoLiaoLocationActivity).color + "\" font-size=\"$fontSize\"px>" + keyString + "</font>"
        }
    }
}